package edu.jimei.projecttachy.controller;

import edu.jimei.projecttachy.entity.DataSource;
import edu.jimei.projecttachy.entity.User;
import edu.jimei.projecttachy.repository.UserRepository;
import edu.jimei.projecttachy.service.DataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;

// DTOs
record DataSourceDto(Long id, String name, String type, String status, Instant created) {
    public static DataSourceDto fromEntity(DataSource ds) {
        return new DataSourceDto(ds.getId(), ds.getName(), ds.getType(), ds.getStatus(), ds.getCreated());
    }
}

record DataSourceRequest(String name, String type, String status) {}


@RestController
@RequestMapping("/api/datasources")
public class DataSourceController {
    @Autowired
    private DataSourceService dataSourceService;
    @Autowired
    private UserRepository userRepository;

    @GetMapping
    public List<DataSourceDto> getAll() {
        return dataSourceService.findAll().stream()
                .map(DataSourceDto::fromEntity)
                .collect(Collectors.toList());
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public DataSourceDto create(@RequestBody DataSourceRequest request) {
        String userEmail = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userRepository.findByEmail(userEmail)
                .orElseThrow(() -> new RuntimeException("User not found for email: " + userEmail));

        DataSource ds = new DataSource();
        ds.setName(request.name());
        ds.setType(request.type());
        ds.setStatus(request.status());
        ds.setUser(user);
        
        DataSource savedDs = dataSourceService.save(ds);
        return DataSourceDto.fromEntity(savedDs);
    }

    @GetMapping("/{id}")
    public DataSourceDto getById(@PathVariable Long id) {
        return dataSourceService.findById(id)
                .map(DataSourceDto::fromEntity)
                .orElseThrow();
    }

    @PutMapping("/{id}")
    public DataSourceDto update(@PathVariable Long id, @RequestBody DataSourceRequest request) {
        DataSource existingDs = dataSourceService.findById(id)
                .orElseThrow(() -> new RuntimeException("DataSource not found with id: " + id));

        String userEmail = SecurityContextHolder.getContext().getAuthentication().getName();
        if (!existingDs.getUser().getEmail().equals(userEmail)) {
            throw new AccessDeniedException("You do not have permission to edit this data source.");
        }

        existingDs.setName(request.name());
        existingDs.setType(request.type());
        existingDs.setStatus(request.status());

        DataSource updatedDs = dataSourceService.save(existingDs);
        return DataSourceDto.fromEntity(updatedDs);
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable Long id) {
        dataSourceService.delete(id);
    }

} 